package com.wangzh.concurrent.lock.pc;

public class A {

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() ->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }

        }).start();new Thread(() ->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }

        }).start();
        new Thread(() ->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();
        new Thread(() ->{
            for (int i = 0; i < 20; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }).start();
    }

}
//判断等待，业务，通知
class Data{ //资源类
    private int number=0;

//    +1
    public synchronized void increment() throws InterruptedException {
        while (number!=0) {
//            判断
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+",add:"+number);
        this.notifyAll();
    }

    //    -1
    public synchronized void decrement() throws InterruptedException {
        while (number==0) {
//            业务
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+",de:"+number);
        this.notifyAll();
    }


}
